<template>
  <div class="app-container">

    <div class="filter-container">
      <el-select clearable style="width: 130px" class="filter-item" v-model="listQuery.companyId" placeholder="动画公司">
        <el-option v-for="item in companies" :key="item.id" :label="item.chineseName" :value="item.id">
        </el-option>
      </el-select>
      <el-select clearable class="filter-item" style="width: 130px" v-model="listQuery.directorId" placeholder="动画导演">
        <el-option v-for="item in directors" :key="item.id" :label="item.chineseName" :value="item.id">
        </el-option>
      </el-select>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
      <el-button class="filter-item" style="margin-left: 10px;" @click="handleCreate" type="primary"
                 icon="el-icon-edit">添加
      </el-button>
    </div>

    <el-table :data="list" v-loading.body="listLoading" element-loading-text="Loading" border fit highlight-current-row>
      <el-table-column type="index" label='#' align="center" sortable/>
      <el-table-column prop="foreignName" label="外文名" align="center" sortable/>
      <el-table-column prop="chineseName" label="中文名" align="center" sortable/>
      <el-table-column prop="episode" label="话数" align="center" sortable/>
      <el-table-column prop="broadcastStart" label="开始时间" align="center" sortable/>
      <el-table-column prop="broadcastEnd" label="结束时间" align="center" sortable/>
      <el-table-column align="center" label="是否完结">
        <template slot-scope="scope">
          <span v-if="scope.row.finished">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="播出星期">
        <template slot-scope="scope">
          <span>{{showWeek(scope.row)}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否收录">
        <template slot-scope="scope">
          <span v-if="scope.row.included">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="是否观看">
        <template slot-scope="scope">
          <span v-if="scope.row.watched">是</span>
          <span v-else>否</span>
        </template>
      </el-table-column>
      <el-table-column prop="watchTime" label="观看时间" align="center" sortable/>
      <el-table-column prop="star" label="评级" align="center" sortable/>
      <el-table-column prop="remark" label="备注" align="center"/>
      <el-table-column align="center" label="操作" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" @click="handleUpdate(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pagination-container">
      <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
                     :current-page="listQuery.current" :page-sizes="[10,20,30,50]" :page-size="listQuery.size"
                     layout="total, sizes, prev, pager, next, jumper" :total="total">
      </el-pagination>
    </div>

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form :rules="rules" ref="dataForm" :model="temp" label-position="right" label-width="80px"
               style='width: 400px; margin-left:70px;'>

        <el-form-item label="公司" prop="companyId">
          <el-select clearable class="filter-item" v-model="temp.companyId" placeholder="动画公司">
            <el-option v-for="item in companies" :key="item.id" :label="item.chineseName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="导演" prop="directorId">
          <el-select clearable class="filter-item" v-model="temp.directorId" placeholder="动画导演">
            <el-option v-for="item in directors" :key="item.id" :label="item.chineseName" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="外文名" prop="foreignName">
          <el-input v-model="temp.foreignName"/>
        </el-form-item>
        <el-form-item label="中文名" prop="chineseName">
          <el-input v-model="temp.chineseName"/>
        </el-form-item>
        <el-form-item label="话数" prop="episode">
          <el-input-number v-model="temp.episode" :min="0"/>
        </el-form-item>
        <el-form-item label="播出开始" prop="broadcastStart">
          <el-date-picker v-model="temp.broadcastStart" type="month" placeholder="选择日期时间" value-format="yyyy-MM-dd"/>
        </el-form-item>
        <el-form-item label="播出结束" prop="broadcastEnd">
          <el-date-picker v-model="temp.broadcastEnd" type="date" placeholder="选择日期时间" value-format="yyyy-MM-dd"/>
        </el-form-item>
        <el-form-item label="是否完结" prop="finished">
          <el-switch v-model="temp.finished"/>
        </el-form-item>
        <el-form-item label="星期" prop="broadcastWeek">
          <el-select v-model="temp.broadcastWeek" placeholder="请选择">
            <el-option v-for="item in weeks" :key="item.value" :label="item.label" :value="item.value"/>
          </el-select>
        </el-form-item>
        <el-form-item label="是否收录" prop="included">
          <el-switch v-model="temp.included"/>
        </el-form-item>
        <el-form-item label="原因" prop="reasonId" v-show="!temp.included">
          <el-select clearable class="filter-item" v-model="temp.reasonId" placeholder="未收录原因">
            <el-option v-for="item in reasons" :key="item.id" :label="item.reason" :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否观看" prop="watched">
          <el-switch v-model="temp.watched"/>
        </el-form-item>
        <el-form-item label="观看时间" prop="watchTime">
          <el-date-picker v-model="temp.watchTime" type="date" placeholder="选择日期时间" value-format="yyyy-MM-dd"/>
        </el-form-item>
        <el-form-item label="评级" prop="star">
          <el-rate v-model="temp.star" :max="10" :allow-half="true" :colors="['#99A9BF', '#F7BA2A', '#FF9900']"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="temp.remark" type="textarea"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button v-if="dialogStatus==='create'" type="primary" @click="createData">确认</el-button>
        <el-button v-else type="primary" @click="updateData">确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {listAnimePage, createAnime, updateAnime, deleteAnime} from '@/api/anime'
  import {listCompany} from "@/api/company";
  import {listDirector} from "@/api/director";
  import {listReason} from "@/api/reason";

  export default {
    data() {
      return {
        total: null,
        companies: null,
        directors: null,
        reasons: null,
        weeks: [{
          value: '0',
          label: '星期日'
        }, {
          value: '1',
          label: '星期一'
        }, {
          value: '2',
          label: '星期二'
        }, {
          value: '3',
          label: '星期三'
        }, {
          value: '4',
          label: '星期四'
        }, {
          value: '5',
          label: '星期五'
        }, {
          value: '6',
          label: '星期六'
        }],
        list: null,
        listLoading: true,
        listQuery: {
          current: 1,
          size: 10,
          companyId: undefined,
          directorId: undefined,
        },
        temp: {
          id: undefined,
          companyId: undefined,
          directorId: undefined,
          reasonId: undefined,
          foreignName: '',
          chineseName: '',
          episode: undefined,
          broadcastStart: '',
          broadcastEnd: '',
          finished: false,
          broadcastWeek: '',
          included: false,
          watched: false,
          watchTime: '',
          star: undefined,
          remark: ''
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '编辑',
          create: '创建'
        },
        rules: {
          foreignName: [{required: true, message: '外文名不能为空', trigger: 'blur'}],
          chineseName: [{required: true, message: '中文名不能为空', trigger: 'blur'}],
          broadcastStart: [{required: true, message: '开始播出时间不能为空', trigger: 'blur'}],
          broadcastWeek: [{required: true, message: '播出星期不能为空', trigger: 'blur'}],
        },
      }
    },

    created() {
      this.fetchData()
      listCompany().then(response => {
        this.companies = response.data.companyList
      });
      listDirector().then(response => {
        this.directors = response.data.directorList
      });
      listReason().then(response => {
        this.reasons = response.data.reasonList
      });
    },

    filters: {},

    methods: {
      fetchData() {
        this.listLoading = true
        listAnimePage(this.listQuery).then(response => {
          this.list = response.data.records
          this.total = response.data.total
          this.listLoading = false
        })
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        delete this.temp.createTime
        delete this.temp.updateTime
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      handleDelete(row) {
        deleteAnime(row.id).then(response => {
          this.$message({
            message: response.message,
            type: 'success'
          })
          for (const v of this.list) {
            if (v.id === row.id) {
              const index = this.list.indexOf(v)
              this.list.splice(index, 1)
              break
            }
          }
        })
      },
      createData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            createAnime(this.temp).then((response) => {
              this.temp.id = response.data.animeId
              this.list.unshift(this.temp)
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            updateAnime(this.temp).then(() => {
              for (const v of this.list) {
                if (v.id === this.temp.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.temp)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      resetTemp() {
        this.temp = {
          id: undefined,
          companyId: undefined,
          directorId: undefined,
          reasonId: undefined,
          foreignName: '',
          chineseName: '',
          episode: undefined,
          broadcastStart: '',
          broadcastEnd: '',
          finished: false,
          broadcastWeek: '',
          included: false,
          watched: false,
          watchTime: '',
          star: undefined,
          remark: ''
        }
      },
      handleFilter() {
        this.listQuery.current = 1
        this.fetchData()
      },
      handleSizeChange(val) {
        this.listQuery.size = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.listQuery.current = val
        this.fetchData()
      },
      showWeek(row) {
        for (const w of this.weeks) {
          if (w.value === row.broadcastWeek) {
            return w.label
          }
        }
      }
    },

    computed: {}
  }
</script>
